package com.sunshine.lnuplus.view.Splash

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import androidx.lifecycle.AndroidViewModel
import com.sunshine.lnuplus.service.LoadWeatherService
import com.sunshine.lnuplus.utils.DatabaseHelper
import com.sunshine.lnuplus.utils.TimeHelper
import com.sunshine.lnuplus.view.Main.MainActivity
import java.util.*

class SplashViewModel(application: Application) : AndroidViewModel(application) {
    val firstStart: Boolean
    private val databaseList: MutableList<String> = ArrayList()
    private var activity: Activity? = null
    fun setActivity(activity: Activity?) {
        this.activity = activity
    }

    private fun createDatabase() {
        databaseList.add(
                "create table user(" +
                        "uno text primary key," +
                        "upassword text not null)")
        databaseList.add(
                "create table timetable(" +
                        "cname text," +
                        "time text not null," +  //课程加时间作主码，否则数据库中无法储存不同时间同一课程
                        "room text," +
                        "teacher text," +
                        "color text," +
                        "weeks text," +
                        "primary key(cname,time))"
        )
        val databaseHelper = DatabaseHelper(databaseList, getApplication(), "timetable.db", null, 1)
        databaseHelper.writableDatabase
    }

    fun toGetWeather() {
        val getLastUpdateWeatherTime = getApplication<Application>().getSharedPreferences("weather", Context.MODE_PRIVATE)
        val lastDay: Int
        val lastHour: Int
        val lastMinute: Int
        val TimeDifference: Long
        lastDay = getLastUpdateWeatherTime.getInt("lastDay", 0)
        lastHour = getLastUpdateWeatherTime.getInt("lastHour", 0)
        lastMinute = getLastUpdateWeatherTime.getInt("lastMinute", 0)
        TimeDifference = (TimeHelper.getDay() - lastDay) * 1440 + (TimeHelper.getHour() - lastHour) * 60 + (TimeHelper.getMinute() - lastMinute).toLong()
        if (TimeDifference > 60) getApplication<Application>().startService(Intent(getApplication(), LoadWeatherService::class.java))
        if (!firstStart) { //注意context 和 application的startActivity不设置flag会报错，activity没有这个错误
            activity!!.startActivity(Intent(getApplication(), MainActivity::class.java))
            activity!!.finish()
        }
    }

    init {
        val appSetting = application.getSharedPreferences("app_setting", Context.MODE_PRIVATE)
        firstStart = appSetting.getBoolean("first_start", true)
        createDatabase()
    }
}